using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using WixSharp;

namespace Installer;

public static class Generator
{
    public static WixEntity[] GenerateWixEntities(IEnumerable<string> args)
    {
        var versionRegex = new Regex(@"RVT_(\d+)");
        var rootFeature = new Feature("Revit Add-ins", "Select versions to install", true)
        {
            Display = FeatureDisplay.expand
        };
        var allVersionDirs = new List<Dir>();

        foreach (var directory in args)
        {
            var directoryInfo = new DirectoryInfo(directory);
            var match = versionRegex.Match(directoryInfo.Name);
            if (!match.Success) continue;

            var versionNumber = match.Groups[1].Value;
            var revitYear = $"20{versionNumber}";
            var publishDir = Path.Combine(directory, "publish");

            if (!Directory.Exists(publishDir))
            {
                Console.WriteLine($"跳过版本 {revitYear}: publish 目录不存在");
                continue;
            }

            // 为每个版本创建一个独立的 Feature
            var versionFeature = new Feature($"Revit {revitYear}", $"Install for Revit {revitYear}", true);
            rootFeature.Children.Add(versionFeature);

            // 使用新方法，递归地为目录下的每个文件创建独立的 File 实体
            var versionFileEntities = CreateFileEntitiesForDir(publishDir, versionFeature);

            // 构建该版本的最终安装目录结构
            var yearDir = new Dir(revitYear, versionFileEntities.ToArray());
            allVersionDirs.Add(yearDir);

            Console.WriteLine($"配置版本 {revitYear} 完成。");
        }

        // 构建统一的、共享的顶级目录结构
        var autodeskDir = new Dir(@"%CommonAppDataFolder%\Autodesk",
            new Dir("Revit",
                new Dir("Addins",
                    allVersionDirs.ToArray())));

        return new WixEntity[] { rootFeature, autodeskDir };
    }

    // 递归地为一个目录及其所有子目录创建WixEntity（Dir和File）列表
    // 这种方法通过为每个文件创建单独的File对象来强制实现文件隔离
    private static List<WixEntity> CreateFileEntitiesForDir(string sourceDir, Feature feature)
    {
        var entities = new List<WixEntity>();

        // 添加当前目录下的所有文件
        foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.TopDirectoryOnly))
        {
            // 为每个文件创建一个独立的File对象，并将其与正确的Feature关联
            entities.Add(new WixSharp.File(feature, file));
        }

        // 递归处理所有子目录
        foreach (var subDir in Directory.GetDirectories(sourceDir))
        {
            var dirName = new DirectoryInfo(subDir).Name;
            // 为子目录创建一个Dir对象，其内容是递归调用的结果
            var subDirEntities = CreateFileEntitiesForDir(subDir, feature);
            entities.Add(new Dir(dirName, subDirEntities.ToArray()));
        }

        return entities;
    }
}